<?php

namespace chemicle\wechat\work\api;

use chemicle\wechat\util\Http;

/**
 * api请求基类,封装网络请求等常用方法
 */
abstract class Base
{

    const URI_PREFIX_QYAPI = 'https://qyapi.weixin.qq.com/cgi-bin';
    
    protected $accessTokenKey = 'access_token';
    
    protected $accessTokenValue = '';
    
    /**
     * 
     * @param string $token
     */
    public function setAccessToken($token)
    {
        $this->accessTokenValue = $token;
    }

    /**
     * 在请求的企业微信接口后面附加token信息
     * @param array $queryParams url参数 引用
     */
    protected function appendToken(&$queryParams)
    {
        $queryParams[$this->accessTokenKey] = $this->accessTokenValue;
    }

    /**
     * 发起Get请求
     * @param string $url 网址 + 路径,不带参数的部分
     * @param array $queryParams 请求参数
     * @param bool $appendedToken
     * @return Object
     */
    protected function get($url, $queryParams = [], $appendedToken = true)
    {
        if ($appendedToken) {
            $this->appendToken($queryParams);
        }
        if ($queryParams) {
            $url .= '?' . http_build_query($queryParams);
        }
        
        return json_decode(Http::get(static::URI_PREFIX_QYAPI . $url));
    }

    /**
     * 发起Post请求
     * @param string $url
     * @param mixed $data
     * @param bool $isPostFile
     * @param array $queryParams
     * @param bool $appendedToken
     * @return Object
     */
    protected function post($url, $data, $isPostFile = false, $queryParams = [], $appendedToken = true)
    {
        if ($appendedToken) {
            $this->appendToken($queryParams);
        }
        
        if ($queryParams) {
            $url .= '?' . http_build_query($queryParams);
        }
        
        return json_decode(Http::post(static::URI_PREFIX_QYAPI . $url, $data, $isPostFile));
    }

}
